(function () {
    // 需要给外部库暴漏查询版本的接口用于升级

    // console.log(window.location.href)


    function jsonMsg(content) {
        let msg = {
            Id: new Date().getTime().toString(),
            Kind: "test",
            Content: content
        }
        return JSON.stringify(msg)
    }


    const WS_SERVER_URL = 'ws://localhost:24824/550eXUE8400eXUE29b41d4a6444uXUEiofnxc/20240718/'
    function createWebSocketConnection(url) {
        var ws = new WebSocket(url)
        ws.onopen = function (event) {
            console.log("WebSocket 连接已打开")
        }
        ws.onmessage = function (event) {
            console.log("收到消息: " + event.data)
        }
        ws.onclose = function (event) {
            console.log("WebSocket 连接已关闭")
        }
        ws.onerror = function (error) {
            console.error("WebSocket 出现错误:", error)
        }
        return ws
    }

    //  let ws = createWebSocketConnection(WS_SERVER_URL)
    //  setInterval(function() {
    //     if (ws.readyState==WebSocket.OPEN){
    //        ws.send(jsonMsg("Hello, Server! "+(new Date().toISOString())))
    //     }else if(ws.readyState==WebSocket.CLOSED){
    //        ws = createWebSocketConnection(WS_SERVER_URL)
    //     }
    //  }, 1000)

    // async function get_desktops() {
    //     const { invoke } = window.__TAURI__.tauri
    //     //  console.dir(invoke)
    //     // Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
    //     let msg = await invoke("get_desktops")
    //     console.log(msg)
    //     let obj = JSON.parse(msg)
    //     document.querySelector('#msg').innerHTML = obj.desktops
    // }
    // window.get_desktops = get_desktops


    // "csp": "default-src 'self' blob: data: filesystem: ws: http: https: 'unsafe-eval' 'unsafe-inline'",

    let g_ffmpegProcess
    let g_outputFileName = 'output'
    let g_check_screen_interval
    const INTERVAL=1*1000 

    async function startFfmpeg() {
        /*
        const { Command } = window.__TAURI__.shell
        let NAME = '薛'
        let vfArg = `scale=1024:-1,drawtext=fontfile=bin/msyh.ttf:text='${NAME} %{localtime}':fontsize=12:fontcolor=red:x=1:y=1,drawtext=fontfile=bin/msyh.ttf:text='%{localtime}':x=mod(100*t\\,w):y=abs(sin(t))*h*0.9:box=0:fontcolor=gray@0.4`
        let args = ["-y", "-f", "gdigrab", "-i", "desktop", "-r", "10", "-t", "14400", "-fs", "4096M", "-b:v", "1M", "-vf", vfArg, g_outputFileName]
        //[ff]mpeg 7.0 [sc]reen [re]corder 
        const command = Command.sidecar('bin/ff7scre', args)
        let p = await command.spawn()
        if (p.pid > 0) {
            g_ffmpegProcess = p
        }
       
        */
        const { invoke } = window.__TAURI__.tauri
        let pid = await invoke("start_ffmpeg", { outputFilename: g_outputFileName,watermarkText:'薛' })
        alert(pid)
    }

    async function stopFfmpeg() {
        /*
        // 在页面保存 g_ffmpegProcess 有缺陷，页面刷新和重新载入时会被重置
        if (g_ffmpegProcess && g_ffmpegProcess.pid > 0) {
            await g_ffmpegProcess.write('q')
        }
        const { invoke } = window.__TAURI__.tauri
        // 后台再次关闭,确保能够正确关闭
        let ok1 = await invoke("kill_ffmpeg", { pid: g_ffmpegProcess.pid })
        // 生成文件校验
        let ok2 = await invoke("generate_checksum", { filename: g_outputFileName })
        */
        const { invoke } = window.__TAURI__.tauri
        let ok = await invoke("stop_ffmpeg")
        alert(ok)
    }


    async function check_screen(x = 0, y = 0, w = 500, h = 500, name = 'd:/check_screen', check = true) {
        const { invoke } = window.__TAURI__.tauri
        let ok = await invoke("check_screen", { x, y, w, h, name, check })
        console.log(new Date(), ok)
    }

    async function disable_keyboard() {
        const { invoke } = window.__TAURI__.tauri
        let success = await invoke("disable_keyboard")
        return success
    }
    async function enable_keyboard() {
        const { invoke } = window.__TAURI__.tauri
        let success = await invoke("enable_keyboard")
        return success
    }
    async function setFullscreen(enable = true) {
        const { appWindow } = window.__TAURI__.window
        await appWindow.setFullscreen(enable)
        await appWindow.setAlwaysOnTop(enable)
    }

    async function selectSavePath() {
        const { open } = window.__TAURI__.dialog
        const { desktopDir } = window.__TAURI__.path
        let path=await desktopDir()
        const selected = await open({
            directory: true,
            defaultPath:  path,
        });
        if (Array.isArray(selected)) {
            // user selected multiple directories
            path=selected[0]
        } else if (selected === null) {
            // user cancelled the selection
        } else {
            // user selected a single directory
            path=selected
        }

        const { invoke } = window.__TAURI__.tauri
        let success = await invoke("set_save_path",{path})
        return path
    }


    async function startAll() {
        await startFfmpeg()
        await setFullscreen(true)
        //生成模板
        await check_screen(5, 5, w = 50, h = 50, name = 'd:/template', false)
        //开始截屏,并记录时间
        g_check_screen_interval = setInterval(check_screen, INTERVAL)

    }

    async function stopAll() {
        // 停止截屏
        clearInterval(g_check_screen_interval)
        await stopFfmpeg()
        await setFullscreen(false)
    }


    function initWindowRightMenu() { // 初始化窗口右侧菜单

        let menu = document.createElement("div")
        menu.style = `
            background: wheat;
            position: fixed;
            z-index: 999;
            right: 0;
            top: 50%;
            transform: translate(0, -50%);`

        function creatMenuItem(html, clickFn) {
            let menuItem = document.createElement("div")
            menuItem.style = `
                cursor: pointer;
                margin:5px;
            `
            menuItem.innerHTML = html
            menuItem.onclick = clickFn
            menu.appendChild(menuItem)
        }

        creatMenuItem("进入全屏", async () => {
            await setFullscreen(true)
        })

        creatMenuItem("退出全屏", async () => {
            await setFullscreen(false)
        })

        creatMenuItem("开始录屏", () => {
            // alert('开始录屏')
            startFfmpeg()
        })

        creatMenuItem("停止录屏", () => {
            // alert('停止录屏')
            stopFfmpeg()
        })

        creatMenuItem("生成模板", () => {
            check_screen(5, 5, w = 50, h = 50, name = 'd:/template', false)
            console.log("生成模板")
        })

        creatMenuItem("截屏", () => {
            check_screen()
            console.log("截屏")
        })

        creatMenuItem("禁用键盘startAll", () => {
            // disable_keyboard()
            // console.log("禁用键盘")
            startAll()
        })
        creatMenuItem("启用键盘stopAll", async () => {
            // await enable_keyboard()
            // console.log("启用键盘")
            stopAll()
        })

        creatMenuItem("跳转index", async () => {
            window.location.href = "index.html"
        })
        creatMenuItem("跳转index1", async () => {
            window.location.href = "index1.html"
        })

        creatMenuItem("设置录屏地址", async () => {
            await selectSavePath()
        })

        document.body.appendChild(menu)
    }




    window.onload = function () {
        // 注意此js 在每次加载不同的url 时 都会重新执行
        // console.log('init.js' + new Date())
        initWindowRightMenu()
    }

    window.onbeforeunload=function(){
        // console.log("========beforeunload")
        clearInterval(g_check_screen_interval)
    }
/*
    document.addEventListener('visibilitychange', function() {
        if (document.visibilityState === 'hidden') {
            // 用户离开了当前页面，可能是关闭或跳转
            console.log("========hidden")
        }
        if (document.visibilityState === 'visible') {
            // 页面变为可见，可能是打开、刷新或从其他标签页切回
            console.log("========visible")
        }
    });
*/
   

})()